<?php
/**
 * Created by PhpStorm.
 * User: chenshiqi
 * Date: 2018/9/11
 * Time: 17:28
 */

namespace app\common\model;

/**
 * 登录模型类
 */
class User extends Common
{
    const OUT_LINE = -1;
    const HIDDLE = 0;
    const ON_LINE = 1;

    /**
     * 查询账号密码是否正确
     * @param $mail
     * @param $password
     * @return array|false|\PDOStatement|string|Model
     */
    public function findUser($mail,$password){
        $re = $this->where(['email'=>$mail,'password'=>md5($password)])->find();
        if($re){
            return $re;
        }else{
            return [];
        }
    }

    /**
     * 查询用户信息
     * @param $id
     * @return array|false|\PDOStatement|string|Model
     */
    public function findUserById($id){
        $re = $this->where(['id'=>$id])->field('id,username,status,sign,avatar')->find();
        if($re){
            return $re;
        }else{
            return [];
        }
    }

    /**
     * 查询账号是否存在
     * @param $mail
     * @return array|bool|false|\PDOStatement|string|Model
     */
    public function findUserInfoByMail($mail){
        $re = $this->where('email',$mail)->find();
        if($re){
            return $re;
        }else{
            return false;
        }
    }

    public function getAllUser(){
        $re = $this->field('id,username,status,sign,avatar')->select();
        return $re;
    }

    public function getAllUserExceptMe($user_id){
        $sql = "select a.* ,
if(b.id is not null,0,1) temporary

from chat_user a

left join chat_friend b on a.id = b.friend_id and b.user_id = {$user_id}

where a.id != {$user_id};";

        $re = $this->query($sql);
        return $re;
    }

    public function setStatus($user_id,$status){
        return $this->_edit(['status'=>$status],['id'=>$user_id]);
    }

    /**
     * 获取用户登录状态
     * @param $user_id
     * @return mixed
     *
     */
    public function getUserStatus($user_id){
        $re = $this->field('status')->where('id',$user_id)->find();
        return $re['status'];
    }

    /**
     * 获取用户额外信息
     * @param $user_id
     */
    public function getUserExtraInfo($user_id){
        $re = $this->alias('u')
            ->join(['chat_extra_user_info'=>'eui'],'eui.user_id = u.id','left')
            ->where(['u.id'=>$user_id])
            ->field('eui.*,u.username,u.sign,u.email,u.avatar')
            ->find();
        if($re){
            return $re;
        }else{
            return [];
        }
    }
}